package com.changgou.canal.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.content.feign.ContentFeign;
import com.changgou.content.pojo.Content;
import com.changgou.web.item.feign.PageFeign;
import com.xpand.starter.canal.annotation.*;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * @author zhengjd
 * @date 2020/5/7 20:43
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@CanalEventListener
public class CanalDataEventListener {

    @Autowired
    ContentFeign contentFeign;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PageFeign pageFeign;

    /**
     * 增加数据监听
     * @param eventType
     * @param rowData
     */
    @InsertListenPoint
    public void onEventInsert(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        rowData.getAfterColumnsList().forEach((c)-> System.out.println("By--Annotation:"+c.getName()+"::  "+c.getValue()));
    }

    /**
     * 修改数据监听
     * @param rowData
     *//*
    @UpdateListenPoint
    public void onEventUpdate(CanalEntry.RowData rowData){
        System.out.println("updateListenPoint");
        rowData.getAfterColumnsList().forEach((c)-> System.out.println("By--Annotation:"+c.getName()+"::  "+c.getValue()));
    }*/

    /**
     * 删除数据监听
     * @param eventType
     */
    @DeleteListenPoint
    public void onEventDelete(CanalEntry.EventType eventType){
        System.out.println("deleteListenPoint");
    }

    /**
     * 自定义监听,修改Redis中的广告缓存
     * @param eventType
     * @param rowData
     */
    @ListenPoint(destination = "example",
            schema = "changgou_content",
            table = {"tb_content_category", "tb_content"},
            eventType = {
                    CanalEntry.EventType.UPDATE,
                    CanalEntry.EventType.INSERT,
                    CanalEntry.EventType.DELETE
            })
    public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        System.out.println("updateListenPoint");
        //获取列名为categoryId的值
        String categoryId = getColumnValue(eventType,rowData);
        //调用feign 获取该分类下的所有广告的集合
        Result<List<Content>> listResult = contentFeign.findByCategoryId(Long.valueOf(categoryId));
        List<Content> contentList = listResult.getData();
        //使用redisTemplate将广告集合存储到Redis中
        stringRedisTemplate.boundValueOps("content_"+categoryId).set(JSON.toJSONString(contentList));

    }


    /**
     * 监听商品spu的数据变动
     * @param eventType
     * @param rowData
     */
    @ListenPoint(destination = "example",
            schema = "changgou_goods",
            table = "tb_spu",
            eventType = {
                    CanalEntry.EventType.UPDATE,
                    CanalEntry.EventType.INSERT,
                    CanalEntry.EventType.DELETE
            })
    public void onEventSpuUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        //判断操作类型(删除时)
        if (eventType == CanalEntry.EventType.DELETE){
            String spuId = "";
            //如果为删除，获取删除之前的数据
            List<CanalEntry.Column> columnsList = rowData.getBeforeColumnsList();
            for (CanalEntry.Column column : columnsList) {
                if (column.getName().equals("id")){
                    spuId = column.getValue();
                    break;
                }
            }
            //根据spuId删除静态页面（通过IO流删除静态页面，后期可能需要删除存放在Nginx中的静态资源） todo

        }else {
            String spuId = "";
            //数据为新增或者更新(获取之后的数据)
            List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
            for (CanalEntry.Column column : afterColumnsList) {
                if (column.getName().equals("id")){
                    spuId=column.getValue();
                    break;
                }

            }
            //调用生成静态页面的item微服务的feign
            pageFeign.createHtml(Long.valueOf(spuId));
        }
    }



    /**
     * 获取列名为categoryId的值
     * @param eventType
     * @param rowData
     * @return
     */
    private String getColumnValue(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        String categoryId = "";

        //如果是删除，则获取beforeList
        if (eventType == CanalEntry.EventType.DELETE){
            for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
                if (column.getName().equalsIgnoreCase("category_id")){
                    categoryId = column.getValue();
                    return categoryId;
                }
            }
        }
        //如果是添加或修改，则获取AfterList
        else{
            for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
                if (column.getName().equalsIgnoreCase("category_id")){
                    categoryId = column.getValue();
                    return categoryId;
                }
            }
        }
        return categoryId;
    }


}
